﻿using System;
using System.Collections.Generic;
using System.IO;

namespace AnimationPackerEngine
{
    public static class PathExt
    {
        public static string RelativePathTo(string from, string to)
        {
            if (string.IsNullOrEmpty(from))
            {
                throw new ArgumentNullException("Argument 'from' is invalid.");
            }

            if (string.IsNullOrEmpty(to))
            {
                throw new ArgumentNullException("Argument 'to' is invalid.");
            }

            if (Path.IsPathRooted(from) && Path.IsPathRooted(to))
            {
                if (string.Compare(Path.GetPathRoot(from), Path.GetPathRoot(to), true) != 0)
                {
                    return to;
                }
            }

            List<string> listPaths = new List<string>();
            string[] fromDirs = from.Split(Path.DirectorySeparatorChar);
            string[] toDirs = to.Split(Path.DirectorySeparatorChar);

            int nLength = Math.Min(fromDirs.Length, toDirs.Length);

            int nLastCommonRoot = -1;

            for (int x = 0; x != nLength; ++x)
            {
                if (string.Compare(fromDirs[x], toDirs[x], true) != 0)
                {
                    break;
                }

                nLastCommonRoot = x;
            }

            if (nLastCommonRoot == -1)
            {
                return to;
            }

            for (int x = nLastCommonRoot + 1; x < fromDirs.Length; ++x)
            {
                if (fromDirs[x].Length > 0)
                {
                    listPaths.Add("..");
                }
            }

            for (int x = nLastCommonRoot + 1; x < toDirs.Length; ++x)
            {
                listPaths.Add(toDirs[x]);
            }

            return string.Join(Path.DirectorySeparatorChar.ToString(), listPaths.ToArray());
        }
    }
}
